package ecs

import (
	"strconv"
	"tushare/common"
	"tushare/model/aliyun/ecs"
	"tushare/service/aliyunCli"

	"github.com/gin-gonic/gin"
	"github.com/golang-module/carbon"
)

func InstallHadoop(c *gin.Context) {
	us := new(common.UserSession)
	userInfo := us.GetUserInfo(c)
	nowTime := carbon.Now().ToDateTimeString()

	count := ecs.AliyunEcsCount(userInfo.Id)
	if count >= 10 {
		c.JSON(200, gin.H{"code": 1, "message": "机器已达上线"})
		c.Abort()
		return
	}

	ae := ecs.AliyunEcs{}
	ae.CreateTime = nowTime
	ae.Status = 0
	ae.TaskType = "install_hadoop"
	ae.UserId = userInfo.Id
	ae.TaskRemark = "任务已提交等待创建"
	ecs.AliyunEcsCreate(ae)
	c.JSON(200, gin.H{"code": 0, "message": "成功"})
}

func CreateEcs(c *gin.Context) {
	regionId := c.Query("region_id")
	zoneId := c.Query("zone_id")
	instanceType := c.Query("instance_type")

	us := new(common.UserSession)
	userInfo := us.GetUserInfo(c)
	if userInfo.Name != "super" {
		c.JSON(200, gin.H{"code": 1, "message": "没有权限无法创建"})
		c.Abort()
		return
	}
	nowTime := carbon.Now().ToDateTimeString()

	count := ecs.AliyunEcsCount(userInfo.Id)
	if count >= 10 {
		c.JSON(200, gin.H{"code": 1, "message": "机器已达上线"})
		c.Abort()
		return
	}

	ae := ecs.AliyunEcs{}
	ae.RegionId = regionId
	ae.ZoneId = zoneId
	ae.InstanceType = instanceType
	ae.CreateTime = nowTime
	ae.Status = 0
	ae.TaskType = "create_ecs"
	ae.UserId = userInfo.Id
	ae.TaskRemark = "任务已提交等待创建"
	ecs.AliyunEcsCreate(ae)
	c.JSON(200, gin.H{"code": 0, "message": "成功"})
}

func EcsAppList(c *gin.Context) {
	instanceId := c.Query("instance_id")
	us := new(common.UserSession)
	userInfo := us.GetUserInfo(c)

	data := ecs.AliyunEcsAppByUserId(userInfo.Id, instanceId)

	c.JSON(200, gin.H{"code": 0, "message": "成功", "data": data})
}

func DeleteInstance(c *gin.Context) {
	id, _ := strconv.ParseInt(c.Query("id"), 10, 64)
	instanceId := c.Query("instance_id")
	di := new(aliyunCli.DeleteInstance)
	di.DeleteInstance(instanceId)

	ecsObj := ecs.AliyunEcs{}
	ecsObj.IsDelete = 1
	ecs.AliyunEcsUpdate(id, ecsObj)
	c.JSON(200, gin.H{"code": 0, "message": "成功"})
}
